package models

import (
	"github.com/go-gorp/gorp"
	"github.com/revel/modules/db/app"
	r "github.com/revel/revel"
)

var (
	Dbm *gorp.DbMap
)

func InitDB() {
	db.Init()
	Dbm = &gorp.DbMap{Db: db.Db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}}

	setColumnSizes := func(t *gorp.TableMap, colSizes map[string]int) {
		for col, size := range colSizes {
			t.ColMap(col).MaxSize = size
		}
	}

	//配置用户表
	t := Dbm.AddTableWithName(User{}, "user").SetKeys(true, "UserId")
	t.ColMap("Password").Transient = true

	//配置商品表
	t = Dbm.AddTableWithName(Item{}, "item").SetKeys(true, "Id")
	setColumnSizes(t, map[string]int{
		"Name":       64,
		"Intro":      1024,
		"Spec":       2048,
		"SmImage":    512,
		"FirstImage": 512,
		"Images":     4096,
	})

	//配置商户信息表
	t = Dbm.AddTableWithName(MerChant{}, "merchant").SetKeys(true, "Id")
	setColumnSizes(t, map[string]int{
		"Name":         64,
		"Tel":          32,
		"Addr":         512,
		"MainProducts": 4096,
	})

	//配置订单信息
	t = Dbm.AddTableWithName(Order{}, "order").SetKeys(true, "Id")
	setColumnSizes(t, map[string]int{
		"Items":    10000,
		"Delivery": 10000,
	})

	Dbm.TraceOn("[gorp]", r.INFO)
	Dbm.CreateTablesIfNotExists()

	// bcryptPassword, _ := bcrypt.GenerateFromPassword(
	// 	[]byte("123456"), bcrypt.DefaultCost)
	// demoUser := &User{0, "游客", "游客", "123456", bcryptPassword, }
	// if err := Dbm.Insert(demoUser); err != nil {
	// 	panic(err)
	// }

	//缓存所有的商品数据
	items, err := Dbm.Select(Item{}, `select * from item`)
	if err != nil {
		panic(err)
	}
	for i := 0; i < len(items); i++ {
		item := items[i].(*Item)
		r.INFO.Printf("get item %d %s", item.SallerId, item.Name)
		CacheSetItem(item)
	}
}
